#!/usr/bin/env python3
"""
模型管理器模块
提供统一的模型访问接口，封装字典访问方式
"""

from typing import Any, Optional

from speech_convert.utils.console_style import print_error, print_success

from ..config.logging_config import LoggerMixin


class ModelManager(LoggerMixin):
    """模型管理器 - 提供统一的模型访问接口"""

    def __init__(self, models: dict[str, Any]):
        """
        初始化模型管理器

        Args:
            models: 包含所有加载模型的字典
        """
        self._models = models

        # 验证必需的模型是否存在
        self._validate_models()
        self.logger.info("✅ 模型管理器初始化完成")

    def _validate_models(self) -> None:
        """验证模型是否正确加载"""
        required_models = ["asr", "asr_streaming", "vad"]
        for model_name in required_models:
            if model_name not in self._models:
                print_error(f"必需的模型 '{model_name}' 未找到")
                raise ValueError(f"必需的模型 '{model_name}' 未找到")
            if self._models[model_name] is None:
                print_error(f"模型 '{model_name}' 加载失败")
                raise ValueError(f"模型 '{model_name}' 加载失败")
            else:
                print_success(f"模型 '{model_name}' 验证通过")

    @property
    def asr(self) -> Any:
        """ASR 语音识别离线模型"""
        return self._models["asr"]

    @property
    def asr_streaming(self) -> Any:
        """ASR 语音识别在线流式模型"""
        return self._models["asr_streaming"]

    @property
    def vad(self) -> Any:
        """VAD 语音活动检测模型"""
        return self._models["vad"]

    @property
    def speaker(self) -> Any | None:
        """说话人识别模型 (可选)"""
        return self._models.get("speaker")

    @property
    def punc(self) -> Any | None:
        """标点符号模型 (可选)"""
        return self._models.get("punc")

    @property
    def has_speaker_model(self) -> bool:
        """检查是否有说话人识别模型"""
        return self.speaker is not None

    @property
    def has_punc_model(self) -> bool:
        """检查是否有标点符号模型"""
        return self.punc is not None

    def get_model(self, model_name: Optional[str]) -> Any:
        """
        通用模型获取方法

        Args:
            model_name: 模型名称

        Returns:
            模型实例或None
        """
        return self._models.get(model_name)

    def list_models(self) -> dict[str, bool]:
        """
        列出所有模型的可用状态

        Returns:
            模型名称和是否可用的映射
        """
        return {name: model is not None for name, model in self._models.items()}

    def get_model_info(self) -> dict[str, Any]:
        """
        获取模型信息摘要

        Returns:
            包含模型状态的信息字典
        """
        return {
            "total_models": len(self._models),
            "loaded_models": sum(
                1 for model in self._models.values() if model is not None
            ),
            "available_models": self.list_models(),
            "required_models_ok": all(
                self._models.get(name) is not None
                for name in ["asr", "asr_streaming", "vad"]
            ),
            "optional_features": {
                "speaker_identification": self.has_speaker_model,
                "punctuation": self.has_punc_model,
            },
        }

    def __repr__(self) -> str:
        """字符串表示"""
        info = self.get_model_info()
        return (
            f"ModelManager("
            f"loaded={info['loaded_models']}/{info['total_models']}, "
            f"speaker={self.has_speaker_model}, "
            f"punc={self.has_punc_model}"
            f")"
        )
